package com.kool.kadmin.mqtt.controller;

import com.kool.kadmin.common.bean.PageListResult;
import com.kool.kadmin.common.bean.Result;
import com.kool.kadmin.common.util.ResultUtil;
import com.kool.kadmin.mqtt.bean.MqttUserDo;
import com.kool.kadmin.mqtt.request.*;
import com.kool.kadmin.mqtt.service.MqttAuthService;
import com.kool.kadmin.mqtt.vo.UserTopicPermitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author luyu
 */
@RestController
@Slf4j
public class MqttAuthController {
    @Resource
    private MqttAuthService authService;

    /**
     * 登记用户
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/register")
    public Result register(@RequestBody @Valid RegisterReq request) {
        authService.register(request);
        return ResultUtil.success();
    }

    /**
     * 关闭用户
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/closeUser")
    public Result closeUser(@RequestBody @Valid CloseUserReq request) {
        authService.closeUser(request);
        return ResultUtil.success();
    }

    /**
     * 激活用户
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/openUser")
    public Result openUser(@RequestBody @Valid OpenUserReq request) {
        authService.openUser(request);
        return ResultUtil.success();
    }

    /**
     * 分页查询用户
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/getMqttUserPage")
    public PageListResult<MqttUserDo> getMqttUserPage(@RequestBody @Valid GetMqttUserPageReq request) {
        return authService.getMqttUserPage(request);
    }

    /**
     * 授权主题
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/topicPermit")
    public Result topicPermit(@RequestBody @Valid TopicPermitReq request) {
        authService.topicPermit(request);
        return ResultUtil.success();
    }

    /**
     * 分页查询用户的主题权限
     *
     * @param request
     * @return
     */
    @PostMapping("/mqtt/getUserTopicAuthPage")
    public PageListResult<UserTopicPermitVo> getUserTopicAuthPage(@RequestBody @Valid GetUserTopicAuthPageReq request) {
        return authService.getUserTopicAuthPage(request);
    }

    /**
     * 同步用户、主题权限数据到kauth
     *
     * @return
     */
    @PostMapping("/mqtt/syncKauthRedis")
    public Result syncKauthRedis() {
        new Thread(() -> {
            try {
                authService.syncKauthRedis();
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }).start();
        return ResultUtil.success();
    }
}
